package com.sbwebsocket.core.service;

import com.sbwebsocket.core.redis.CycleProcessUnusualOfflineClientMessage;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalTime;

/**
 * 主节点选取及相应工作处理
 * @Auther: GSJ
 * @Date: 2022/2/17
 * @Description:
 * @version: 1.0
 */
//@Component
@Slf4j
public class MasterServerWork {

    private static final String WS_MASTER_LOCK="WS:MASTER:LOCK";

    @Autowired
    CycleProcessUnusualOfflineClientMessage cycleProcessUnusualOfflineClientMessage;

    @Autowired
    private RedissonClient redissonClient;

    private RLock lock;

    private void getLock(){
        this.lock = redissonClient.getLock(WS_MASTER_LOCK);
        this.lock.lock();
    }

    /**
     * master节点注册
     * @return
     */
    protected boolean masterRegister(){
        //TODO:如果首次拿到锁，后面与redis断了，锁过期后，需要处理此方法后继的定时任务
        getLock();
        return true;
    }


    public void work(){
        boolean b = masterRegister();
        if(b){
            if(log.isDebugEnabled()){
                log.debug("master开始处理异常消息时间:{}", LocalTime.now());
            }
            cycleProcessUnusualOfflineClientMessage.processUnsualClientMsg();
        }
    }
}
